<?php

namespace app\v1\controller;

use support\Request;
use app\model\PayPingModel;
use app\model\OrderModel;
use app\model\UserModel;
use app\model\Util;
use app\model\BizGoodsOrderModel;
use app\model\BizPayRecordModel;
use app\model\BizModel;

/**
 * 点评控制器
 * 处理点评相关操作
 */
class PingController
{
    /**
     * 提交点评
     * @param Request $request
     * @return mixed
     */
    public function submit(Request $request)
    {
        try {
            $user = $request->userLogin;

            // 参数验证
            $input = $request->post('data');
            $orderId = $input['order_id'];
            $rating = $input['rating'];
            $content = $input['content'];
            $images = $input['images'];
            $type = $input['type'];

            if($user->in_black > 0){
                throw new \Exception('您当前处于禁言状态，无法进行点评');
            }

            if (empty($orderId)) {
                throw new \Exception('订单ID不能为空');
            }

            if (empty($rating) || $rating < 1 || $rating > 5) {
                throw new \Exception('请选择星级评分(1-5星)');
            }

            // 验证用户登录状态
            $userId = $request->userLogin->id;

            if($type == 'biz-order'){
                // 验证订单是否存在且属于当前用户
                $order = BizGoodsOrderModel::where('id', $orderId)
                    ->where('user_id', $userId)
                    ->first();
                if (!$order) {
                    throw new \Exception('订单不存在或不属于您');
                }

                // 检查是否已经点评过
                $existingPing = PayPingModel::where('item_id', '=',$orderId)->where('type', '=',$type)->first();
                if ($existingPing) {
                    throw new \Exception('该订单已点评过');
                }

                // 创建点评记录
                $pingData = [
                    'item_id' => $orderId,
                    'user_id' => $userId,
                    'goods_id' => $order->biz_goods_id,
                    'biz_id' => $order->biz_id,
                    'type' => $type,
                    'star' => $rating,
                    'content' => $content,
                    'images' => $images,
                    'created_at' => date('Y-m-d H:i:s'),
                    'updated_at' => date('Y-m-d H:i:s')
                ];
            }else if($type == 'pay'){
                $record = BizPayRecordModel::find($orderId);
                if (!$record) {
                    throw new \Exception('支付记录不存在');
                }

                // 检查是否已经点评过
                $existingPing = PayPingModel::where('item_id', '=',$orderId)->where('type', '=',$type)->first();
                if ($existingPing) {
                    throw new \Exception('该订单已点评过');
                }

                $pingData = [
                    'item_id' => $orderId,
                    'user_id' => $userId,
                    'goods_id' => 0,
                    'biz_id' => $record->biz_id,
                    'type' => $type,
                    'star' => $rating,
                    'content' => $content,
                   'images' => $images,
                    'created_at' => date('Y-m-d H:i:s'),
                    'updated_at' => date('Y-m-d H:i:s')
                ];
            }else if($type == 'store-order'){
                $order = OrderModel::find($orderId);
                if (!$order) {
                    throw new \Exception('订单不存在');
                }

                $existingPing = PayPingModel::where('item_id', '=',$orderId)->where('type', '=',$type)->first();
                if ($existingPing) {
                    throw new \Exception('该订单已点评过');
                }

                
                
                $pingData = [
                    'item_id' => $orderId,
                    'user_id' => $userId,
                    'goods_id' => 0,
                    'biz_id' => 0,
                    'type' => $type,
                    'star' => $rating,
                    'content' => $content,
                    'images' => $images,
                    'created_at' => date('Y-m-d H:i:s'),
                    'updated_at' => date('Y-m-d H:i:s')
                ];
            }

            $ping = PayPingModel::create($pingData);

            if(in_array($type,['pay','biz-order'])){
                $biz = BizModel::find($ping->biz_id);
                $biz->syncStar();
            }

            if($type == 'pay'){
                $record->ping_id = $ping->id;
                $record->save();
            }else if($type == 'biz-order'){
                $order->ping_id = $ping->id;
                $order->save();
            }else if($type == 'store-order'){
                $order->ping_id = $ping->id;
                $order->save();
            }

            return json([
                'data' => $ping,
                'msg' => '点评提交成功',
                'code' => 1
            ]);
        } catch (\Exception $e) {
            return json([
                'data' => null,
                'msg' => $e->getMessage(),
                'code' => 0
            ]);
        }
    }

    /**
     * 获取订单点评详情
     * @param Request $request
     * @return mixed
     */
    public function detail(Request $request)
    {
        try {
            $orderId = $request->get('order_id');
            $userId = $request->get('user_id');

            if (empty($orderId)) {
                throw new \Exception('订单ID不能为空');
            }

            if (empty($userId)) {
                throw new \Exception('请先登录');
            }

            // 获取点评详情
            $ping = PayPingModel::where('order_id', $orderId)
                ->where('user_id', $userId)
                ->first();

            if (!$ping) {
                throw new \Exception('点评不存在');
            }

            // 处理图片数据
            if (!empty($ping->images)) {
                $images = json_decode($ping->images, true);
                $ping->images = $images ?: [];
            } else {
                $ping->images = [];
            }

            return json([
                'data' => $ping,
                'msg' => '获取点评详情成功',
                'code' => 1
            ]);
        } catch (\Exception $e) {
            return json([
                'data' => null,
                'msg' => $e->getMessage(),
                'code' => 0
            ]);
        }
    }

    /**
     * 获取商家点评列表
     * @param Request $request
     * @return mixed
     */
    public function list(Request $request)
    {
        try {
            $bizId = $request->get('biz_id');
            $page = $request->get('page', 1);
            $pageSize = $request->get('page_size', 10);

            if (empty($bizId)) {
                throw new \Exception('商家ID不能为空');
            }

            // 获取点评列表
            $query = PayPingModel::where('biz_id', $bizId)
                ->with(['user' => function($query) {
                    $query->select('id', 'nickname', 'avatar');
                }]);

            $total = $query->count();
            $list = $query->orderBy('created_at', 'desc')
                ->offset(($page - 1) * $pageSize)
                ->limit($pageSize)
                ->get();

            // 处理数据
            foreach ($list as $item) {
                // 处理图片数据
                if (!empty($item->images)) {
                    $images = json_decode($item->images, true);
                    $item->images = $images ?: [];
                } else {
                    $item->images = [];
                }

                // 处理用户头像
                if ($item->user && !empty($item->user->avatar)) {
                    $item->user->avatar = Util::pathToUrl($item->user->avatar);
                }

                // 隐藏用户敏感信息
                if ($item->user) {
                    $item->user->nickname = $this->maskNickname($item->user->nickname);
                }
            }

            return json([
                'data' => [
                    'list' => $list,
                    'total' => $total,
                    'page' => $page,
                    'page_size' => $pageSize
                ],
                'msg' => '获取点评列表成功',
                'code' => 1
            ]);
        } catch (\Exception $e) {
            return json([
                'data' => null,
                'msg' => $e->getMessage(),
                'code' => 0
            ]);
        }
    }

    /**
     * 获取用户点评列表
     * @param Request $request
     * @return mixed
     */
    public function userList(Request $request)
    {
        try {
            $userId = $request->get('user_id');
            $page = $request->get('page', 1);
            $pageSize = $request->get('page_size', 10);

            if (empty($userId)) {
                throw new \Exception('请先登录');
            }

            // 获取用户点评列表
            $query = PayPingModel::where('user_id', $userId)
                ->with(['order' => function($query) {
                    $query->select('id', 'order_no', 'total_amount');
                }]);

            $total = $query->count();
            $list = $query->orderBy('created_at', 'desc')
                ->offset(($page - 1) * $pageSize)
                ->limit($pageSize)
                ->get();

            // 处理数据
            foreach ($list as $item) {
                // 处理图片数据
                if (!empty($item->images)) {
                    $images = json_decode($item->images, true);
                    $item->images = $images ?: [];
                } else {
                    $item->images = [];
                }
            }

            return json([
                'data' => [
                    'list' => $list,
                    'total' => $total,
                    'page' => $page,
                    'page_size' => $pageSize
                ],
                'msg' => '获取我的点评列表成功',
                'code' => 1
            ]);
        } catch (\Exception $e) {
            return json([
                'data' => null,
                'msg' => $e->getMessage(),
                'code' => 0
            ]);
        }
    }

    /**
     * 隐藏用户昵称
     * @param string $nickname
     * @return string
     */
    private function maskNickname($nickname)
    {
        if (empty($nickname)) {
            return '匿名用户';
        }

        $length = mb_strlen($nickname);
        if ($length <= 2) {
            return mb_substr($nickname, 0, 1) . '*';
        } else {
            return mb_substr($nickname, 0, 1) . str_repeat('*', $length - 2) . mb_substr($nickname, -1);
        }
    }
} 